package com.lgx.right.dao.impl;

import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.lgx.common.basic.dao.GeneralDao;
import com.lgx.common.exception.DataException;
import com.lgx.right.dao.IUserExpandDao;
import com.lgx.right.entity.UserExpand;

/**
 * 
 * @author acer
 *
 */
@Component("userExpandDao")
public class UserExpandDao extends GeneralDao implements IUserExpandDao {

	protected Logger log = Logger.getLogger(this.getClass());
	
	public UserExpand createUserExpand(UserExpand userExpand) throws DataException {
		this.getHibernateTemplate().save(userExpand);
		log.info("[创建用户扩展]:"+userExpand.getId());
		return userExpand;
	}

	public UserExpand updateUserExpand(UserExpand userExpand) throws DataException {
		this.getHibernateTemplate().update(userExpand);
		log.info("[更新用户扩展]:"+userExpand.getId());
		return userExpand;
	}

	public void deleteUserExpand(UserExpand userExpand) throws DataException {
		log.info("[删除用户扩展]:"+userExpand.getId());
		this.getHibernateTemplate().delete(userExpand);
	}

	public void deleteUserExpandById(long id) throws DataException {
		log.info("[删除用户扩展]:"+id);
		this.deleteUserExpand(this.findUserExpandById(id));
	}

	public UserExpand findUserExpandById(long id) {
		return this.getHibernateTemplate().get(UserExpand.class, id);
	}
	
	@SuppressWarnings("unchecked")
	public UserExpand findUserExpandByUserId(long userId){
		String sql = "from UserExpand u where u.user.id = "+userId+" order by u.id asc";
		List<UserExpand> UserExpands =  this.getHibernateTemplate().find(sql);
		if(UserExpands.size() == 0){
			return null;
		}
		return UserExpands.get(0);
	}
	
	@SuppressWarnings("unchecked")
	public List<UserExpand> findUserExpandListByPoints(long userId,int x,int y){
		String sql = "from UserExpand e" +
				" where sqrt(power(abs("+x+"-substring_index(e.points,',',1)),2)+power(abs("+y+"-substring_index(e.points,',',-1)),2)) <1000" +
				" and e.user.id != " + userId +
				" order by sqrt(power(abs("+x+"-substring_index(e.points,',',1)),2)+power(abs("+y+"-substring_index(e.points,',',-1)),2)) asc";
		return this.getHibernateTemplate().find(sql);
	}
	
	@SuppressWarnings("unchecked")
	public List<UserExpand> findUserExpandList(){
		String sql = "from UserExpand u order by u.id asc";
		return this.getHibernateTemplate().find(sql);
	}
}
